package com.example.homeworkmutualevaluation.Controller;

import com.example.homeworkmutualevaluation.Service.FileService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController {
    @Resource
    private FileService fileService;

    @PostMapping("/upload")
    public Map<String, Object> upload(@RequestParam MultipartFile file) {
        HashMap<String, Object> response = new HashMap<>();
        String fileid = fileService.upload(file);
        if (fileid != null) {
            response.put("code", 1);
            response.put("fileid", fileid);
        } else response.put("code", 0);
        return response;
    }

    @GetMapping("/download/{fileid}")
    public void download(@PathVariable String fileid, HttpServletResponse response) {
        fileService.download(fileid, response);
    }

    @GetMapping("/img/{fileid}")
    public void getImg(@PathVariable String fileid, HttpServletResponse response) {
        fileService.getImg(fileid, response);
    }

    @PostMapping("/get_file_name")
    public Map<String, Object> getFileName(@RequestParam String fileid) {
        HashMap<String, Object> response = new HashMap<>();
        String fileName = fileService.getFileName(fileid);
        if (fileName != null) {
            response.put("code", 1);
            response.put("data", fileName);
        } else {
            response.put("code", 0);
            response.put("msg", "文件不存在");
        }
        return response;
    }
}
